let hot;
let currentDocId = null;
let currentUser = null;
let authToken = localStorage.getItem('token');
let currentPage = 1;
let docsPerPage = 5;
let allDocs = [];
let isDocListExpanded = false;

// 初始化Handsontable
function initSpreadsheet(data = []) {
    const container = document.getElementById('excel-container');
    hot = new Handsontable(container, {
        data: data,
        rowHeaders: true,
        colHeaders: true,
        contextMenu: true,
        height: '100%',
        licenseKey: 'non-commercial-and-evaluation',
        readOnly: true,
        columns: getColumnSettings(data)
    });
}

// 根据数据动态生成列设置
function getColumnSettings(data) {
    const maxColumns = data.length > 0 ? data[0].length : 3;
    const columns = [];
    for (let i = 0; i < maxColumns; i++) {
        columns.push({});
    }
    return columns;
}

// 检查登录状态
async function checkAuth() {
    if (!authToken) {
        showAuthContainer();
        return;
    }

    try {
        showLoading('正在验证登录状态...');
        const response = await fetch('/api/me', {
            method: 'GET',
            headers: new Headers({ 'Authorization': `Bearer ${localStorage.getItem('token')}` })
        });
        hideLoading();

        if (response.ok) {
            currentUser = await response.json();
            showMainContainer();
            loadDocumentList();
        } else {
            showAuthContainer();
            const error = await response.json();
            console.log(error)
            showAuthError(error.message);
        }
    } catch (error) {
        hideLoading();
        console.error('验证失败:', error);
        showAuthError('验证登录状态时发生错误');
    }
}

// 加载文档列表
async function loadDocumentList() {
    try {
        showLoading('正在加载文档列表...');
        const response = await fetch('/api/docs', {
            headers: { 'Authorization': `Bearer ${authToken}` }
        });
        hideLoading();

        allDocs = await response.json();
        showDocsByPage(currentPage);
    } catch (error) {
        hideLoading();
        alert('加载文档列表失败');
    }
}

// 按页显示文档
function showDocsByPage(page) {
    const startIndex = (page - 1) * docsPerPage;
    const endIndex = startIndex + docsPerPage;
    const currentDocs = allDocs.slice(startIndex, endIndex);

    const listHtml = currentDocs.map(doc => `
        <div class="doc-list-item" onclick="openDocument(${doc.id})">
            <div class="d-flex justify-content-between">
                <div>${doc.title}</div>
                <small class="text-muted">${new Date(doc.created_at).toLocaleDateString()}</small>
            </div>
        </div>
    `).join('');

    document.getElementById('doc-list-content').innerHTML = listHtml;
    showPagination();
}

// 显示分页导航
function showPagination() {
    const totalPages = Math.ceil(allDocs.length / docsPerPage);
    const paginationHtml = [];

    for (let i = 1; i <= totalPages; i++) {
        paginationHtml.push(`
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" onclick="goToPage(${i})">${i}</a>
            </li>
        `);
    }

    document.getElementById('doc-list-pagination').innerHTML = `
        <ul class="pagination">
            ${paginationHtml.join('')}
        </ul>
    `;
}

// 跳转到指定页面
function goToPage(page) {
    currentPage = page;
    showDocsByPage(currentPage);
}

// 切换文档列表展开/收起状态
function toggleDocList() {
    const docListContent = document.getElementById('doc-list-content');
    const docListPagination = document.getElementById('doc-list-pagination');
    const toggleButton = document.getElementById('toggle-doc-list');

    if (isDocListExpanded) {
        docListContent.style.display = 'none';
        docListPagination.style.display = 'none';
        toggleButton.textContent = '展开文档列表';
    } else {
        docListContent.style.display = 'block';
        docListPagination.style.display = 'block';
        toggleButton.textContent = '收起文档列表';
    }

    isDocListExpanded = !isDocListExpanded;
}

// 打开文档
async function openDocument(docId) {
    currentDocId = docId;
    try {
        showLoading('正在打开文档...');
        const response = await fetch(`/api/docs/${docId}`, {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        });
        hideLoading();

        const docData = await response.json();

        hot.loadData(docData.content);
        checkLockStatus();
        startLockPolling();
    } catch (error) {
        hideLoading();
        alert('加载文档失败');
    }
}

// 保存文档
async function saveDocument() {
    const content = hot.getData();

    try {
        showLoading('正在保存文档版本...');
        await fetch(`/api/docs/${currentDocId}/versions`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({ content })
        });
        hideLoading();

        alert('保存成功');
    } catch (error) {
        hideLoading();
        alert('保存失败');
    }
}

// 检查文档锁定状态
async function checkLockStatus() {
    try {
        showLoading('正在检查文档锁定状态...');
        const response = await fetch(`/api/docs/${currentDocId}/lock-status`, {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        });
        hideLoading();

        if (response.ok) {
            const { is_locked, locked_by } = await response.json();
            if (is_locked && locked_by !== currentUser.username) {
                hot.updateSettings({ readOnly: true });
                updateLockStatus(true, locked_by);
            } else {
                updateLockStatus(false);
            }
        } else {
            const error = await response.json();
            alert('检查锁定状态失败: ' + error.message);
        }
    } catch (error) {
        hideLoading();
        console.error('检查锁定状态时出错:', error);
        alert('检查锁定状态失败');
    }
}

// 获取编辑锁
async function requestEditLock() {
    try {
        showLoading('正在请求编辑权限...');
        const response = await fetch(`/api/docs/${currentDocId}/lock`, {
            method: 'POST',
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        });
        hideLoading();

        if (response.ok) {
            hot.updateSettings({ readOnly: false });
            updateLockStatus(true, currentUser.username);
        } else {
            const error = await response.json();
            alert(error.message);
        }
    } catch (error) {
        hideLoading();
        alert('获取编辑权限失败');
    }
}

// 更新锁状态显示
function updateLockStatus(isLocked, lockedBy = null) {
    const statusElement = document.getElementById('lock-status');
    const ownerElement = document.getElementById('lock-owner');

    if (isLocked && lockedBy === currentUser.username) {
        statusElement.className = 'badge bg-success';
        statusElement.textContent = '编辑模式';
        ownerElement.textContent = '';
    } else if (isLocked) {
        statusElement.className = 'badge bg-danger';
        statusElement.textContent = '已被锁定';
        ownerElement.textContent = `正在编辑：${lockedBy}`;
    } else {
        statusElement.className = 'badge bg-secondary';
        statusElement.textContent = '只读模式';
        ownerElement.textContent = '';
    }
}

// 启动锁状态轮询
function startLockPolling() {
    setInterval(async () => {
        try {
            const response = await fetch(`/api/docs/${currentDocId}/lock-status`, {
                headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
            });
            const { is_locked, locked_by } = await response.json();

            if (is_locked && locked_by !== currentUser.username) {
                hot.updateSettings({ readOnly: true });
                updateLockStatus(true, locked_by);
            }
        } catch (error) {
            console.error('锁状态检查失败:', error);
        }
    }, 10000);
}

// 显示版本历史
async function showVersionHistory() {
    try {
        showLoading('正在加载版本历史...');
        const response = await fetch(`/api/docs/${currentDocId}/versions`, {
            headers: { 'Authorization': `Bearer ${localStorage.getItem('token')}` }
        });
        hideLoading();

        const versions = await response.json();

        const versionHtml = versions.map(v => `
            <div class="card mb-2">
                <div class="card-body">
                    <h6>版本 ${v.version}</h6>
                    <small class="text-muted">
                        ${new Date(v.created_at).toLocaleString()} 
                        由 ${v.created_by.username}
                    </small>
                </div>
            </div>
        `).join('');

        document.getElementById('version-list').innerHTML = versionHtml;
        new bootstrap.Modal('#versionHistoryModal').show();
    } catch (error) {
        hideLoading();
        alert('加载版本历史失败');
    }
}

// 显示登录注册容器
function showAuthContainer() {
    document.getElementById('auth-container').style.display = 'block';
    document.getElementById('main-container').style.display = 'none';
}

// 显示主界面容器
function showMainContainer() {
    document.getElementById('auth-container').style.display = 'none';
    document.getElementById('main-container').style.display = 'block';
}

// 显示加载状态
function showLoading(message) {
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading-spinner';
    const text = document.createTextNode(message);
    loadingDiv.appendChild(text);
    document.body.appendChild(loadingDiv);
}

// 隐藏加载状态
function hideLoading() {
    const loadingDiv = document.querySelector('.loading-spinner');
    if (loadingDiv) {
        document.body.removeChild(loadingDiv);
    }
}

// 显示认证错误信息
function showAuthError(message) {
    const errorDiv = document.getElementById('auth-error');
    errorDiv.textContent = message;
}

// 登录
async function login() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        showLoading('正在登录...');
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        hideLoading();

        if (response.ok) {
            const data = await response.json();
            authToken = data.token;
            localStorage.setItem('token', authToken);
            checkAuth();
        } else {
            const error = await response.json();
            showAuthError(error.message);
        }
    } catch (error) {
        hideLoading();
        showAuthError('登录时发生错误');
    }
}

// 注册
async function register() {
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        showLoading('正在注册...');
        const response = await fetch('/api/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });
        hideLoading();

        if (response.ok) {
            alert('注册成功，请登录');
        } else {
            const error = await response.json();
            showAuthError(error.message);
        }
    } catch (error) {
        hideLoading();
        showAuthError('注册时发生错误');
    }
}

// 退出登录
function logout() {
    localStorage.removeItem('token');
    authToken = null;
    showAuthContainer();
}

// 显示创建文档模态框
function showCreateDocModal() {
    new bootstrap.Modal('#createDocModal').show();
}
// 创建文档
async function createDocument() {
    const title = document.getElementById('newDocTitle').value;
    if (!title) {
        alert('请输入文档标题');
        return;
    }

    try {
        showLoading('正在创建文档...');
        const response = await fetch('/api/docs', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({ title })
        });
        hideLoading();

        if (response.ok) {
            const newDoc = await response.json();
            loadDocumentList();
            alert('文档创建成功');
        } else {
            const error = await response.json();
            alert('创建文档失败: ' + error.message);
        }
    } catch (error) {
        hideLoading();
        console.log(error)
        alert('创建文档时发生错误');
    } finally {
        $('#createDocModal').modal('hide')
    }
}

// 初始化
function init() {
    initSpreadsheet();
    checkAuth();
}

window.onload = init;